package cn.powertime.evaluation.file.storage;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.DateFormatUtil;
import cn.powertime.evaluation.entity.SysFile;
import cn.powertime.evaluation.exception.FileServerException;
import cn.powertime.evaluation.file.storage.config.DefaultDiskProperties;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  文件存储的默认实现，使用本地磁盘存储
 * </p>
 *
 * @author ZYW
 * @version v1.0.0
 * @date 2019-08-23 11:48
 */
public class DefaultFileStorage implements FileStorage {

    private DefaultDiskProperties defaultProperties;

    public DefaultFileStorage(DefaultDiskProperties defaultProperties) {
        this.defaultProperties = defaultProperties;
    }

    @Override
    public FileInfo write(MultipartFile file) {

        LocalDateTime now = LocalDateTime.now();
        String uploadFolder = now.format(DateTimeFormatter.ofPattern(DateFormatUtil.YYYYMMdd));

        String path = defaultProperties.getPath();

        if (StringUtils.endsWith(path, Constants.PATH_SEPARATOR_LINUX)
                || StringUtils.endsWith(path, Constants.PATH_SEPARATOR_WIN)) {
            path = path + uploadFolder;
        } else {
            path = path + File.separator + uploadFolder;
        }

        File pathFile = new File(path);
        if (!pathFile.exists() && !pathFile.mkdirs()) {
            throw new FileServerException("创建文件夹失败！");
        }

        String origName = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(origName);
        String newFileName = now.format(DateTimeFormatter.ofPattern(DateFormatUtil.YYYYMMddHHmmssSSS)) + "." + extName;
        long size = file.getSize();
        try {
            String targetPath = pathFile + File.separator + newFileName;
            file.transferTo(new File(targetPath));

        } catch (IOException e) {
            throw new FileServerException("上传文件File为空！", e);
        }
        return FileInfo.builder()
                .name(newFileName)
                .ext(extName)
                .origName(origName)
                .path(path)
                .size(Long.valueOf(size).intValue())
                .build();
    }

    @Override
    public void read(SysFile file, HttpServletResponse response) {
        final String fileName = file.getName();
        final String filePath = file.getPath();
        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(filePath)) {
            throw new FileServerException("文件路径或者名称为空！");
        }
        String downloadPath = filePath + File.separator + fileName;
        String origName = file.getOrigName();
        try {
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String filename = URLEncoder.encode(origName, "UTF-8");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            File downloadFile = new File(downloadPath);
            if (!downloadFile.exists()) {
                throw new FileServerException(downloadPath + "文件不存在！");
            }
            Files.copy(downloadFile.toPath(), response.getOutputStream());
        } catch (IOException e) {
            throw new FileServerException("下载文件异常！", e);
        }
    }
}
